package br.com.salmos;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Locale;

import android.R.id;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import br.com.salmos.dao.SALMOSEPContentProvider;
import br.com.salmos.dao.SALMOSESContentProvider;
import br.com.salmos.dao.SALMOSPTContentProvider;
import br.com.salmos.dao.SQLOpenHelperSalmos;
import br.com.salmos.dao.TableSalmosENHelper;
import br.com.salmos.dao.TableSalmosESHelper;
import br.com.salmos.dao.TableSalmosPTHelper;
import br.com.salmos.vo.Versiculo;

public class SalmosActivity extends Activity {

	private final String PT = "pt";
	private final String ES = "es";

	TextView txtTexto;
	TextView txtVersiculo;
	private final int SOBRE = 0;
	private final int AJUDA = 1;
	
	Intent it;
	
	//ContentProvider cp;
	SALMOSPTContentProvider cpt;
	
	TableSalmosPTHelper tableSalmosPt;
	TableSalmosENHelper tableSalmosEn;
	TableSalmosESHelper tableSalmosEs;
	
	Context ctx;
	
	String idioma;
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		ctx = this;
		//cpt = new SALMOSPTContentProvider();
		//cpt = (SALMOSPTContentProvider) cp;
		//boolean existDB = SQLOpenHelperSalmos.checkDataBaseExistence();
		
		Locale curLocale = java.util.Locale.getDefault();
		idioma = curLocale.getLanguage();
				
		
		tableSalmosPt = new TableSalmosPTHelper(this);
		tableSalmosEn = new TableSalmosENHelper(this);
		tableSalmosEs = new TableSalmosESHelper(this);
		
		SharedPreferences preferences = getSharedPreferences("salmos", 0);        
        int primeiraVez = preferences.getInt("primeiravez", 0);
        
        if(primeiraVez == 0){        	
        	if(idioma.equals("pt")){
        		Toast.makeText(getBaseContext(), "Toque no texto para atualizar o versículo", Toast.LENGTH_LONG).show();
        	}
        	else if (idioma.equals("es")){
        		Toast.makeText(getBaseContext(), "Toque en el texto para actualizar el verso", Toast.LENGTH_LONG).show();
        	} else {
        		Toast.makeText(getBaseContext(), "Tap the text to update the Verse", Toast.LENGTH_LONG).show();
        	}
        	SharedPreferences prefGravando = getSharedPreferences("salmos", MODE_PRIVATE);
    		SharedPreferences.Editor prefEditor = prefGravando.edit();
    		prefEditor.putInt("primeiravez", 1);
    		prefEditor.commit();
        }
		
		
		final ViewFlipper vf = (ViewFlipper) findViewById(R.id.viewFlipper);
		vf.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.slide_in_left));
		vf.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.slide_out_right));
		vf.setFlipInterval(10000);

		txtTexto = (TextView) findViewById(R.id.textView1);
		txtVersiculo = (TextView) findViewById(R.id.textView2);
		
		atualizarTela();
		
		txtTexto.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						vf.showNext();
						atualizarTela();
						
					}
		}); 
		
		txtVersiculo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				vf.showNext();
				atualizarTela();
				
			}
		});
		
//		
//
//		imgBtRefresh.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				vf.showNext();
//				atualizarTela();
//			}
//		});
//		
//		Button btDel = (Button) findViewById(R.id.btdelete);
//		Button btCarrega = (Button) findViewById(R.id.btcarrega);
//		
//		btCarrega.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				
//				//insertEspecial();
//				//loadArchiveInDB();
//				//loadArchiveENInDB();
//				//loadArchiveEPInDB();
//				
//			}
//		});
//		
//		btDel.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				
//				ContentProvider cp = new SALMOSPTContentProvider();
//				clearProverbs(cp, SALMOSPTContentProvider.CONTENT_URI);
//				
//			}
//		});
		
	}

	private void atualizarTela() {				

		Versiculo v = getVersiculo();
		txtTexto.setText(v.getTexto());
		txtVersiculo.setText(v.getLivro() + " " + v.getCapitulo() + ":"
				+ v.getVersiculo());

	}

	public Versiculo getVersiculo() {


//		Locale curLocale = java.util.Locale.getDefault();
//		idioma = curLocale.getLanguage();
		
		Log.i("IDIOMA", idioma);

		Log.i("Vai pegar o texto!", "Pegou!!");
		
		Cursor cursor;
		if(idioma.equals("pt")){
			cursor = tableSalmosPt.getVersiculosDesmarcados();
		} else if (idioma.equals("es")){
			cursor = tableSalmosEs.getVersiculosDesmarcados();
		} else {
			cursor = tableSalmosEn.getVersiculosDesmarcados();
		}
		
		Versiculo v = new Versiculo();

		int aleatorio = 1 + (int) (Math.random() * cursor.getCount());

		int i = 0;
		boolean loop = true;

		if (cursor.getCount() > 0) {

			ContentValues cv = new ContentValues();
			cv.put(SALMOSPTContentProvider.LIDO, 1);

			while (cursor.moveToNext() && loop) {
				if (i == aleatorio) {
				    
				        v.setId(cursor.getInt(cursor.getColumnIndex(TableSalmosPTHelper.COL_ID)));

					v.setLivro(cursor.getString(cursor
							.getColumnIndex(TableSalmosPTHelper.COL_LIVRO)));
					v.setCapitulo(cursor.getInt(cursor
							.getColumnIndex(TableSalmosPTHelper.COL_CAPITULO)));
					v.setVersiculo(cursor.getInt(cursor
							.getColumnIndex(TableSalmosPTHelper.COL_VERSICULO)));
					v.setTexto(cursor.getString(cursor
							.getColumnIndex(TableSalmosPTHelper.COL_TEXTO)));
					loop = false;
					
					tableSalmosPt.updateVersiculoLido(v);
				}
				i++;
			}
		} else {
			//return desmarcaVersiculos(cp, uri);
		}

		return v;

	}

	public Versiculo desmarcaVersiculos(ContentProvider cp, Uri uri) {

		ContentValues cv = new ContentValues();

		cv.put(SALMOSPTContentProvider.LIDO, 0);

		cp.update(uri, cv, null, null);

		return getVersiculo();

	}

	public void loadArchiveENInDB() {
		String arquivo = "/arch/salmosen.txt";

		InputStream is = this.getClass().getResourceAsStream(arquivo);
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(is, "UTF-8");
		} catch (UnsupportedEncodingException e1) {			
			e1.printStackTrace();
		}

		BufferedReader in = new BufferedReader(isr);
		String s;
		String livro = "", texto = "";
		int capitulo = 0, versiculo = 0;
		int indexTexto = 0 ;

		try {
			s = in.readLine();
			while (s != null) {

				livro = s.substring(0, 7).trim();
				livro = livro.toUpperCase();
				
				try{
					//Log.i("CAP",s.substring(7, s.indexOf(":")));
					capitulo = Integer.parseInt(s.substring(7, s.indexOf(":")));
					
					
				} catch (Exception e){
					Log.e("ErroPsalms","Erro de parse capitulo " + capitulo);
				}
				
				try{
					
					versiculo = Integer.parseInt(s.substring(s.indexOf(":") + 1,s.indexOf(":") + 3).trim());					
					texto = s.substring(s.indexOf(":") + 3).trim();
				} catch (Exception e) {
					try{
						
						versiculo = Integer.parseInt(s.substring(s.indexOf(":") + 1,s.indexOf(":") + 2).trim());
						texto = s.substring(s.indexOf(":") + 2).trim();
					} catch (Exception e2){
						Log.e("ErroPsalms","Erro de parse versiculo " + versiculo);
					}
				}

				Log.i("SalmosEN ", capitulo + ":" + versiculo + " - " + texto);
				Versiculo versiculoObject = new Versiculo(texto, livro, capitulo, versiculo);
                tableSalmosEn.insert(versiculoObject);
				
				s = in.readLine();

			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void loadArchiveInDB() {

		String arquivo = "/arch/salmospt.txt";
		
		String livro = "Salmos", texto = "";
		int capitulo = 0, versiculo = 0;

		InputStream is = this.getClass().getResourceAsStream(arquivo);
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(is, "UTF-8");
		} catch (UnsupportedEncodingException e1) {			
			e1.printStackTrace();
		}

		//int ii = 0;

		BufferedReader in = new BufferedReader(isr);
		String s;

		try {
			s = in.readLine();
			while (s != null) {

				if (s.substring(0, 1).equals("+")) {
					livro = s.substring(1);
					capitulo = 0;
					versiculo = 0;

				} else if (s.substring(0, 1).equals(">")) {
					capitulo++;
					versiculo = 0;

				} else {
					versiculo++;
					try{
						int a = Integer.parseInt(s.substring(0,3));
						texto = s.substring(4).trim();
					} catch (Exception e) {
						texto = s.substring(2).trim();
					}
					
					if(capitulo == 120)
						break;

					Log.i("SalmosPT ", capitulo + ":" + versiculo + " - " + texto);
					Versiculo versiculoObject = new Versiculo(texto, livro, capitulo, versiculo);
	                tableSalmosPt.insert(versiculoObject);

				}

				s = in.readLine();
				// ii++;
				// if(ii==40) break;
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	
	
	public void loadArchiveEPInDB() {

		String arquivo = "/arch/salmosep.txt";
		
		String livro = "Salmos", texto = "";
		int capitulo = 0, versiculo = 0;

		InputStream is = this.getClass().getResourceAsStream(arquivo);
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(is, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		//int ii = 0;

		BufferedReader in = new BufferedReader(isr);
		String s;

		try {
			s = in.readLine();
			
			iteracao:
			while (s != null) {
				//Log.i("LineEN ",s);
				if (s.substring(0, 1).equals("+")) {
					livro = s.substring(1);
					capitulo = 0;
					versiculo = 0;

				} else if (s.substring(11).contains("Capítul")) {
					capitulo++;
					versiculo = 0;

				} else {
					if(s.substring(11,14).contains("*")){
						s = in.readLine();
						continue iteracao;
					}
					
					try{
						
						versiculo = Integer.parseInt(s.substring(s.indexOf(":") + 1,s.indexOf(":") + 3).trim());					
						texto = s.substring(s.indexOf(":") + 3).trim();
					} catch (Exception e) {
						try{
							
							versiculo = Integer.parseInt(s.substring(s.indexOf(":") + 1,s.indexOf(":") + 2).trim());
							texto = s.substring(s.indexOf(":") + 2).trim();
						} catch (Exception e2){
							Log.e("ErroPsalms","Erro de parse versiculo " + versiculo);
						}
					}
					
					
					//versiculo++;
					//texto = s.substring(2).trim();
					
					Versiculo versiculoObject = new Versiculo(texto, livro, capitulo, versiculo);
					Log.i("SalmosEN ", capitulo + ":" + versiculo + " - " + texto);
                    tableSalmosEs.insert(versiculoObject);


					
				}

				s = in.readLine();
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	
	/** 
	 * Add menu items
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	public boolean onCreateOptionsMenu(Menu menu) {  
	    menu.add(0, SOBRE, 0, R.string.sobre); 
	    menu.add(0, AJUDA, 0, R.string.ajuda); 
	    return true;  
	}  
	 
	/** 
	 * Define menu action
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	public boolean onOptionsItemSelected(MenuItem item) {  
	    switch (item.getItemId()) {  
	        case SOBRE:  
	        	
	        	Dialog dialog = new Dialog(ctx);                
                dialog.setCancelable(true);
                dialog.setContentView(R.layout.dialogsobre);
                dialog.show();
	        	
	        	break;
	        case AJUDA:	        	
	        	if(idioma.equals("pt")){
	        		Toast.makeText(getBaseContext(), "Toque no texto para atualizar o versículo", Toast.LENGTH_LONG).show();
	        	}
	        	else if (idioma.equals("es")){
	        		Toast.makeText(getBaseContext(), "Toque en el texto para actualizar el verso", Toast.LENGTH_LONG).show();
	        	} else {
	        		Toast.makeText(getBaseContext(), "Tap the text to update the Verse", Toast.LENGTH_LONG).show();
	        	}
	        	break;
		  default:
			// put your code here	  
	    }  
	    return false;  
	}
	
	

}